const VueLoaderPlugin = require('vue-loader/lib/plugin');
const path = require('path');
const chalk = require('chalk');
const webpack = require('webpack');
const webpackDevServer = require('webpack-dev-server');
const HTMLPlugin = require('html-webpack-plugin');//设置.html文件模板/title等
const CleanWebpackPlugin = require('clean-webpack-plugin');//每次打包清理dist插件
const ExtractTextPlugin = require("extract-text-webpack-plugin");//提取css样式插件//webpack4中用mini-css-extract-plugin
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");//压缩css
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");//webpack4中引入压缩css后，js压缩失效，需要手动配置
//const FaviconsWebpackPlugin = require('favicons-webpack-plugin');//页面ico插件,一般在html-webpack插件里面可以设置favicon
const ProgressBarPlugin = require('progress-bar-webpack-plugin')//进度条

const isDev = process.env.NODE_ENV == 'development' && true;//区分环境

const config = {
    mode: process.env.NODE_ENV || 'production',
    target: "web",
    entry: [path.join(__dirname, 'src/main.js')],//为模板文件添加热更新
    output: {
        filename: 'bundle.[hash:8].js',
        path: path.join(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: ['cache-loader',
                    {
                        loader: 'vue-loader',
                        options: {
                            hotReload: /*isDev ? true : false*/false
                        }
                    }]
            },
            // 它会应用到普通的 `.js` 文件
            // 以及 `.vue` 文件中的 `<script>` 块
            {
                test: /\.js$/,
                exclude: file => (
                    /node_modules/.test(file) &&
                    !/\.vue\.js/.test(file)
                ),
                loader: 'babel-loader',
            },
            {
                test: /\.jsx$/,
                loader: 'babel-loader'
            },
            // 它会应用到普通的 `.css` 文件
            // 以及 `.vue` 文件中的 `<style>` 块

            /**/
            {
                test: /\.(gif|png|jpeg|jpg|svg)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 20 * 1024,//最大20k，小于20k转化为base64，否则用file-loader处理
                        name: 'imgs/[name].[hash].[ext]'
                    }
                }]
            },
            {
                test: /\.html$/,
                loader: "raw-loader"
            },
            {
                test:/\.(eot|woff2|woff|ttf|svg)$/,
                loader:'url-loader',
                options: {
                    limit:10000,
                    name:'fonts/[name].[hash:8].[ext]'
                }
            }
        ]
    },
    plugins: [
        // 请确保引入这个插件来施展魔法
        new VueLoaderPlugin(),
        new HTMLPlugin({
            filename: 'index.html',
            template: path.join(__dirname, 'public/index.html'),
            favicon: path.join(__dirname, 'public/favicon.ico'),
            title: 'fuck'//用ejs渲染title不能加全局html-loader
        }),
        new ProgressBarPlugin({
            format: '  build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)',
            clear: false
        }),
    ]
}


if (isDev) {
    config.module.rules.push({
        test: /\.css$/,
        use: [
            'vue-style-loader',
            {
                loader: 'css-loader',
                options: {
                    importLoaders: 2,
                    sourceMap: true
                }
            },
            {
                loader: "postcss-loader",
                options: {
                    sourceMap: true
                }
            }
        ]
    });
    config.module.rules.push({
        test: /\.scss$/,
        use: [
            'vue-style-loader',
            {
                loader: 'css-loader', options: {
                    importLoaders: 2,
                    sourceMap: true
                }
            },
            {
                loader: "postcss-loader",
                options: {
                    sourceMap: true
                }
            },
            'sass-loader'
        ]
    });
    config.devtool = "#cheap-module-eval-source-map";//源码映射
    config.plugins.push(
        new webpack.HotModuleReplacementPlugin()
    );
    config.devServer = {
        port: 8000,
        host: '0.0.0.0',
        overlay: {
            errors: true
        },
        hot: true,
        stats: "errors-only",
        after(...nodes) {
            console.log('hhhh')
        }
    }
} else {
    config.output.filename = 'js/[name].[chunkhash].js';
    config.entry = {
        app: path.join(__dirname, 'src/main.js')
    };
    config.module.rules.push({
        test: /\.css$/,
        use: [
            MiniCssExtractPlugin.loader,
            {
                loader: 'css-loader',
                options: {
                    importLoaders: 2,
                }
            },
            {
                loader: "postcss-loader",
                options: {
                    sourceMap: false
                }
            }
        ]

    });
    config.module.rules.push({
        test: /\.scss$/,
        use: [
            MiniCssExtractPlugin.loader,
            {
                loader: 'css-loader',
                options: {
                    importLoaders: 2,//对于@import的.css，使用后面两个loader
                    sourceMap:false,
                }
            },

            {
                loader: "postcss-loader",
                options: {
                    sourceMap: false,
                }
            },
            'sass-loader'
        ]

    });
    config.optimization = {
        splitChunks: {
            chunks: 'all'
        },
        runtimeChunk: true,
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: true // set to true if you want JS source maps
            }),
            new OptimizeCSSAssetsPlugin({})
        ]
    };
    config.plugins.push(
        // new ExtractTextPlugin('css/style.[name].[chunkhash:8].css'),
        new CleanWebpackPlugin(['dist']),
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: "css/[name]-[chunkhash].css",
            chunkFilename: "css/[name]-[id]-[contenthash].css"
        })
    );
}


module.exports = config;